import { RestProvider } from './../../providers/rest/rest';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Storage } from '@ionic/storage'
import { BaseUI } from '../../common/baseui';
import { ModalController } from 'ionic-angular/components/modal/modal-controller';
import { LoadingController } from 'ionic-angular/components/loading/loading-controller';
import { ToastController } from 'ionic-angular/components/toast/toast-controller';
import { ViewController } from 'ionic-angular/navigation/view-controller';
import { HeadfacePage } from '../headface/headface';
/**
 * Generated class for the UserPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-user',
  templateUrl: 'user.html',
})
export class UserPage extends BaseUI {


  headface: string
  nickname: string = "加载中..."
  errorMessage: any

  constructor(public navCtrl: NavController, 
              public navParams: NavParams,
              public modalCtrl: ModalController,
              public loadCtrl: LoadingController,
              public toastCtrl: ToastController,
              public viewCtrl: ViewController,
              public rest: RestProvider,
              public storage: Storage) {
                super()
  }

  ionViewDidEnter(){
    this.loadUserPage()
   }
 
   loadUserPage() {
     this.storage.get('userId').then((val)=> {
       if(val!=null) {
         // 加载用户数据
         let loading = super.showLoading(this.loadCtrl, "加载中...")
         this.rest.getUserInfo(val)
         .subscribe(
           userinfo => {
             this.nickname = userinfo["UserNickName"]
             this.headface = userinfo["UserHeadface"] + "?" + (new Date()).valueOf()
             loading.dismiss()
           },
          error=> this.errorMessage = <any>error
         )
       }
     })
   }

   updateNickName() {
     this.storage.get('userId').then(val => {
       console.log(val)
       if(val != null) {
         let loading = super.showLoading(this.loadCtrl, '修改中...')
         this.rest.updateNickName(val,this.nickname)
         .subscribe(
           f=> {
             if(f['Status']=='OK') {
               loading.dismiss()
               super.showToast(this.toastCtrl, '昵称修改成功')
             } else {
              loading.dismiss()
              super.showToast(this.toastCtrl, f["StatusContent"])
             }
           },
          error=> this.errorMessage = <any>error          
         )
       }
     })
   }
   logout() {
    this.storage.remove("userId")
    this.viewCtrl.dismiss()
   }

   gotoHeadface() {
     this.navCtrl.push(HeadfacePage)
   }
}
